<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item><nuxt-link to="/meal/manage">餐券管理</nuxt-link></a-breadcrumb-item>
        <a-breadcrumb-item>餐券统计</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-form>
        <a-row>
          <a-col :span="12">
            <a-form-item label="统计日期范围:" v-bind="formItemLayout">
              <a-range-picker v-model="dateSection" allow-clear @change="onChange" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-button :loading="sending" type="primary" @click="handleExport">导出报表</a-button>
          </a-col>
        </a-row>
      </a-form>

      <a-tabs v-model="tabIndex" type="card">
        <a-tab-pane :key="0" tab="总体情况">
          <s-table
            ref="countTable"
            bordered
            class="s-table"
            row-key="name"
            :show-pagination="false"
            :columns="columns"
            :data="loadData"
            :alert="false"
          />
        </a-tab-pane>
        <a-tab-pane :key="1" tab="具体情况">
          <s-table
            ref="SpecificTable"
            bordered
            class="s-table"
            row-key="scheduleDate"
            :show-pagination="false"
            :columns="columnsSpecific"
            :data="loadSpecificData"
            :alert="false"
            :scroll="{ x: 1500}"
          />
          <!-- 分页器 -->
          <div class="pagination-container">
            <a-pagination
              :page-size="queryParam.pageSize"
              :show-total="total => `共 ${total} 条记录 第 ${queryParam.pageNum} / ${Math.ceil(total / queryParam.pageSize)} 页`"
              :current="queryParam.pageNum"
              :total="count"
              show-quick-jumper
              hide-on-single-page
              @change="handlePage"
            />
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>

  </page-view>
</template>

<script>
import { PageView, STable } from '@/components'

const dataColumns = [
  { title: '总数', align: 'center', dataIndex: 'totalQty' },
  { title: '未使用', align: 'center', dataIndex: 'unusedQty' },
  { title: '已使用', align: 'center', dataIndex: 'usedQty' },
  { title: '已过期', align: 'center', dataIndex: 'expiredQty' },
  { title: '换餐数', align: 'center', dataIndex: 'exchangeQty' }
]

export default {
  name: 'Count',
  components: { PageView, STable },
  inject: ['formItemLayout'],
  props: {
    dateStr: {
      type: String,
      default: ''
    }
  },

  data () {
    return {
      tabIndex: 0,
      dateSection: this.dateStr.split(',').filter(i => i).map(i => this.$moment(i)),
      minScheduleDate: this.dateStr.split(',')[0] || '',
      maxScheduleDate: this.dateStr.split(',')[1] || '',
      sending: false,
      queryParam: {
        pageNum: 1,
        pageSize: 10
      },
      // 表头
      columns: [
        { title: '餐券时间', align: 'center', dataIndex: 'name' },
        { title: '总数', align: 'center', dataIndex: 'totalQty' },
        { title: '未使用', align: 'center', dataIndex: 'unusedQty' },
        { title: '已使用', align: 'center', dataIndex: 'usedQty' },
        { title: '已过期', align: 'center', dataIndex: 'expiredQty' },
        { title: '换餐数', align: 'center', dataIndex: 'exchangeQty' }
      ],
      columnsSpecific: [
        { title: '订餐日期', align: 'center', dataIndex: 'scheduleDate' },
        { title: '早餐', align: 'center', children: dataColumns.map(i => Object.assign({}, i, { dataIndex: `${i.dataIndex}0` })) },
        { title: '午餐', align: 'center', children: dataColumns.map(i => Object.assign({}, i, { dataIndex: `${i.dataIndex}1` })) },
        { title: '晚餐', align: 'center', children: dataColumns.map(i => Object.assign({}, i, { dataIndex: `${i.dataIndex}2` })) }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const params = { pageNum: -1 }
        const { maxScheduleDate, minScheduleDate, $get } = this
        if (maxScheduleDate) params.maxScheduleDate = maxScheduleDate
        if (minScheduleDate) params.minScheduleDate = minScheduleDate
        return this.$axios.post('api/mealCoupon/queryOverall', params).then(res => {
          return { data: $get(res, 'data.data.dataList', []) }
        }).catch(e => {
          this.$notification.error({ message: '连接服务器超时' })
        })
      },
      count: 0,
      loadSpecificData: parameter => {
        const { maxScheduleDate, minScheduleDate, queryParam, $get } = this
        const params = queryParam
        if (maxScheduleDate) params.maxScheduleDate = maxScheduleDate
        if (minScheduleDate) params.minScheduleDate = minScheduleDate
        return this.$axios.post('api/mealCoupon/querySpecific', params).then(res => {
          this.count = $get(res, 'data.data.count', 0) // 设置总数
          const data = $get(res, 'data.data.dataList', []).map(item => {
            const { mealCouponTotalVoList = [] } = item
            const nameList = ['早餐', '午餐', '晚餐']
            const names = mealCouponTotalVoList.map(meal => {
              const { name, totalQty, unusedQty, usedQty, expiredQty, exchangeQty } = meal
              const index = nameList.indexOf(name)
              if (index === -1) return false
              const setData = {
                [`totalQty${index}`]: totalQty,
                [`unusedQty${index}`]: unusedQty,
                [`usedQty${index}`]: usedQty,
                [`expiredQty${index}`]: expiredQty,
                [`exchangeQty${index}`]: exchangeQty
              }
              Object.assign(item, setData)
              return name
            })
            this.$difference(nameList, names).forEach(name => {
              const index = nameList.indexOf(name)
              if (index === -1) return false
              Object.assign(item, {
                [`totalQty${index}`]: 0,
                [`unusedQty${index}`]: 0,
                [`usedQty${index}`]: 0,
                [`expiredQty${index}`]: 0,
                [`exchangeQty${index}`]: 0
              })
            })
            return item
          })
          return { data }
        }).catch(e => {
          this.$notification.error({ message: '连接服务器超时' })
        })
      }
    }
  },

  methods: {
    handlePage (p) {
      this.$handlePage(p)
    },

    onChange (date, dateString) {
      this.minScheduleDate = dateString[0]
      this.maxScheduleDate = dateString[1]
      this.$refs.countTable.refresh()
      this.$refs.SpecificTable.refresh()
    },

    async handleExport () {
      const { tabIndex, minScheduleDate, maxScheduleDate } = this
      this.$toggleSending(1)
      const url = ['exportOverall', 'exportSpecific'][tabIndex]
      const str = ['总体情况', '具体情况'][tabIndex]
      const param = { pageNum: -1, minScheduleDate, maxScheduleDate }
      await this.$exportFile({ url: `api/mealCoupon/${url}`, param, fileName: `餐券统计报表_${str}_${minScheduleDate}-${maxScheduleDate}` })
      this.$toggleSending()
    }

  }

}
</script>

<style lang="less" scoped>

</style>
